<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2024/1/4 10:35
 * Desc: 景点订单信息
 */
class Service_Api_Member_Order_Spot extends Service_Api_Order
{
    public function detail(int $mid, int $id, $order = array()): array
    {
        if (empty($order)) {
            $order = DB::select()
                ->from('member_order')
                ->where('id', '=', $id)
                ->execute()
                ->current();
        }

        $order = Model_Member_Order::order_info($order['ordersn']);

        $order['status_name'] = Model_Member_Order::$order_status[$order['status']];
        $order['litpic']      = Model_Api_V2_System::reorganized_resource_url($order['litpic']);

        // 产品编号
        $order['series'] = St_Product::product_series($order['productautoid'], $order['typeid']);

        //会员信息
        $order['member_info'] = DB::select('nickname', 'truename', 'email', 'mobile', 'litpic')
            ->from('member')
            ->where('mid', '=', $order['memberid'])
            ->execute()
            ->current();
        if (!empty($order['member_info'])) {
            $order['member_info']['litpic'] = Model_Api_V2_System::reorganized_resource_url($order['member_info']['litpic']);
        }

        // 会员折扣
        if (St_Functions::is_normal_app_install('memberdiscount')) {
            if ($order['paytype'] == 2) {
                $order['member_discount_price'] = Model_Discount::get_order_discount($id);
            }
        }

        // 订单金额处理
        $order['totalprice'] = $order['totalprice'] - $order['iscoupon']['cmoney'] - $order['jifentprice'] - $order['platform_discount'] - $order['envelope_price'];

        // 卡券支付
        $order['card_pay'] = false;
        if (St_Functions::is_normal_app_install('system_card')) {
            $order['card_pay'] = DB::select()
                ->from('card_member_reservation_record')
                ->where('order_sn', '=', $order['ordersn'])
                ->execute()
                ->valid();
        }

        // 钱包支付
        $order['wallet_pay'] = 0;
        if (St_Functions::is_normal_app_install('system_wallet')) {
            $wallet_log = DB::select()
                ->from('wallet_log')
                ->where('order_sn', '=', $order['ordersn'])
                ->and_where('type', '=', 3)
                ->execute()
                ->current();
            if ($wallet_log) {
                $order['wallet_pay'] = $wallet_log['use_amount'];
            }
        }

        // 判断订单是否结束
        if ($order['status'] == 1 && $order['auto_close_time'] > 0) {
            if ($order['auto_close_time'] < time()) {
                // 订单关闭
                $order['status'] = 3;
            } else {
                // 计算结束秒数
                $order['close_second'] = $order['auto_close_time'] - time();
            }
        }

        // 优惠券信息处理
        if (!isset($order['iscoupon'])) {
            $order['iscoupon'] = array(
                'name' => null,
                'money' => 0
            );
        }

        $order['addtime'] = $order['addtime'] ? date('Y-m-d H:i:s', $order['addtime']) : '';
        $order['paytime'] = $order['paytime'] ? date('Y-m-d H:i:s', $order['paytime']) : '';

        // 退款信息处理
        $order['apply_time']  = '';
        $order['refund_time'] = '';
        if (in_array($order['status'], array(4, 6))) {
            $refund_build = DB::select()
                ->from('member_order_refund')
                ->where('ordersn', '=', $order['ordersn']);
            if ($order['status'] == 4) {
                $refund_build->and_where('status', '=', 1);
            } else {
                $refund_build->and_where('status', '=', 0);
            }
            $refund_info          = $refund_build->execute()->current();
            $order['apply_time']  = $refund_info['addtime'] ? date('Y-m-d H:i:s', $refund_info['addtime']) : '';
            $order['refund_time'] = $refund_info['modtime'] ? date('Y-m-d H:i:s', $refund_info['modtime']) : '';
        }

        if ($order['status'] == 6) {
            $addtime             = DB::select()
                ->from('member_order_refund')
                ->where('ordersn', '=', $order['ordersn'])
                ->and_where('status', '=', 0)
                ->execute()
                ->get('addtime');
            $order['apply_time'] = $addtime ? date('Y-m-d H:i:s', $addtime) : '';
        }


        // 套餐信息处理
        $suits = array();
        $show_eticketno = in_array($order['status'], array(2, 5));
        if ($order['haschild']) {
            $child_order = DB::select()
                ->from('member_order')
                ->where('pid', '=', $id)
                ->and_where('memberid', '=', $mid)
                ->execute()
                ->as_array();
            foreach ($child_order as $item) {
                $suits[] = $this->get_suit_info($item, $show_eticketno);
            }
        } else {
            $suits[] = $this->get_suit_info($order, $show_eticketno);
        }

        // 验单数量
        $current_verified_num = 0;
        foreach ($suits as $suit) {
            $current_verified_num = bcadd($current_verified_num, $suit['current_verified_num'], 0);
        }
        $order['current_verified_num'] = $current_verified_num;

        $order['suits'] = $suits;

        // 订单信息处理
        $order = $this->unset_order_info($order);

        ksort($order);
        return $order;
    }

    /**
     * 套餐信息处理
     * @param $order
     * @param $show_eticketno bool 是否展示票码
     * @return array
     */
    private function get_suit_info($order, $show_eticketno)
    {
        $order_id = $order['id'];
        $num      = intval($order['dingnum']);
        $data     = array(
            'order_id' => $order_id,
            'productname' => $order['productname'],
            'suit_name' => $order['suit_name'],
            'name' => $order['suit_name'],
            'dingnum' => $num,
            'num' => $num,
            'price' => $order['price'],
            'usedate' => $order['usedate'],
            'status' => $order['status'],
            'isconsume' => $order['isconsume'],
            'eticketno' => '',
            'web_url' => Common::get_web_url($order['webid'])
        );
        $sku_info = Model_Member_Order_Sku::get_order_sku($order_id);
        if ($sku_info && !empty($sku_info['period_time']['des'])) {
            $data['usedate'] .= ' ' . $sku_info['period_time']['des'];
        }


        // 游客信息
        $tourers = Model_Member_Order_Tourer::get_tourer_by_orderid($order_id);
        foreach ($tourers as $key => $val) {
            $tourers[$key] = array(
                'id' => $val['id'],
                'tourername' => $val['tourername'],
                'cardtype' => $val['cardtype'],
                'cardnumber' => $val['cardnumber'],
                'must_carry' => (bool)$val['cardnumber'],
            );
        }
        $data['tourers'] = $tourers;

        if($show_eticketno) {
            // 有供应商且开启显示二维码
            if ($order['supplierlist'] && Model_Supplier::display_is_open()) {
                $data['eticketno'] = $order['eticketno'];
            }

            //stccs升级部分，票二维码显示
            if (St_Functions::is_normal_app_install('supplier_spot_stccs')) {
                $stccs_tickets          = DB::select()
                    ->from('member_order_stccs_ticket_guid')
                    ->where('orderid', '=', $order['id'])
                    ->execute()
                    ->as_array();
                $data["stccs_tickets"] = $stccs_tickets;
            }

            // 票付通
            if (St_Functions::is_normal_app_install('system_docs')) {
                $docs = DB::select()
                    ->from('member_order_docs')
                    ->where("ordersn", '=', $order['ordersn'])
                    ->and_where('UUcode','!=','')
                    ->execute()
                    ->as_array();
                if ($docs && $order['status'] == 2) {
                    foreach ($docs as &$v) {
                        $v['ticket_num']  = $v['UUcode'];
                        $v['ticket_guid'] = $v['UUcode'];
                        $v['status']      = 2;
                    }
                    $data["stccs_tickets"] = $docs;
                }
            }

            // 如果不是以上的情况，则使用普通消费码
            if (empty($data["stccs_tickets"])) {
                if (!empty($order['eticketno'])) {
                    $list                         = DB::select(
                        array('b.dingnum', 'verified_dingnum'),
                        array('b.childnum', 'verified_childnum'),
                        array('b.oldnum', 'verified_oldnum'),
                        array('b.addtime', 'verified_addtime'))
                        ->from(array('member_order', 'a'))
                        ->join(array('member_order_verify', 'b'), 'LEFT')
                        ->on('a.id', '=', 'b.orderid')
                        ->where('a.status', 'in', array('2', '5'))
                        ->and_where_open()
                        ->where('a.isconsume', '=', 1)
                        ->or_where('b.id', 'IS NOT', null)
                        ->and_where_close()
                        ->and_where('a.eticketno', '=', $order['eticketno'])
                        ->execute()
                        ->as_array();
                    $data['current_verified_num'] = 0;
                    foreach ($list as $vel) {
                        $data['current_verified_num'] = bcadd($data['current_verified_num'], $vel['verified_dingnum'], 0);
                    }
                } else {
                    $data['current_verified_num'] = 0;
                }
            }
        }

        return $data;
    }

    /**
     * 删除门票订单不需要的字段
     * @param $order
     * @return array
     */
    private function unset_order_info($order)
    {
        unset($order['memberid']);
        unset($order['webid']);
        unset($order['productaid']);
        unset($order['express_company']);
        unset($order['express_num']);
        unset($order['express_total_price']);
        unset($order['childprice']);
        unset($order['childnum']);
        unset($order['oldnum']);
        unset($order['oldprice']);
        unset($order['online_transaction_no']);
        unset($order['payment_proof']);
        unset($order['people4_num']);
        unset($order['people4_price']);
        unset($order['people5_num']);
        unset($order['people5_price']);
        unset($order['people6_num']);
        unset($order['people6_price']);
        unset($order['receiver_address_id']);
        unset($order['receiver_address_infos']);
        unset($order['roombalance']);
        unset($order['roombalance_paytype']);
        unset($order['roombalancenum']);
        unset($order['saleman']);
        unset($order['supplierorderexdata']);
        unset($order['api_channel_orderno']);
        unset($order['admin_remark']);
        unset($order['contract_id']);
        unset($order['departdate']);
        unset($order['distributororderexdata']);
        unset($order['distributor']);
        unset($order['member_info']['id']);

        return $order;
    }
}